/*
 * @Descripttion: 
 * @version: 
 * @Author: 
 * @Date: 2022-04-25 11:40:02
 * @LastEditors: weidelong
 * @LastEditTime: 2022-04-27 17:55:36
 */
const express = require('express')
const jwt = require("../jwt/jwt")
const user = require('../db/userSchema')
const doctor = require('../db/doctorSchema')

/* 使用express中的Router对象 */
const router = express.Router()

router.post('/login', async (req, res) => {
	const { userName, password } = req.body
	let userObj = await user.findOne({userName})
	if (userObj) {
		// 有该用户，验证密码
		let passwordDb = userObj.password
		if (passwordDb == password) {
			// 密码正确,生成token
			let token = jwt.generateToken(userObj['userName'], 60 * 60 * 1) // 1小时
			res.send({
				status: 200,
				data: {
					code: 0,
					token,
					username: userObj.userName,
                    identity: 'manager'
				},
				msg: '登录成功'
			})
		} else {
			res.send({
				status: 404,
				msg: '密码错误'
			})
		}
	} else {
		res.send({
			status: 404,
			msg: '账号不存在'
		})
	}
})

// 医师登录
router.post('/doctorlogin', async (req, res) => {
	const { userName, password } = req.body
	let userObj = await doctor.findOne({userName})
	if (userObj) {
		// 有该用户，验证密码
		let passwordDb = userObj.password
		if (passwordDb == password) {
			// 密码正确,生成token
			let token = jwt.generateToken(userObj['userName'], 60 * 60 * 1) // 1小时
			res.send({
				status: 200,
				data: {
					code: 0,
					token,
					id: userObj.id,
					username: userObj.userName,
                    identity: 'doctor'
				},
				msg: '登录成功'
			})
		} else {
			res.send({
				status: 404,
				msg: '密码错误'
			})
		}
	} else {
		res.send({
			status: 404,
			msg: '账号不存在'
		})
	}
})

// 获取医师信息
router.get('/selectDoctorInfo', async (req, res) => {
	const { userName } = req.query
	console.log(req.query)
	let doctorInfo = await doctor.find({userName})
	if (doctorInfo) {
		const obj = {
			id: doctorInfo.id,
			phone: doctorInfo.phone,
			name: doctorInfo.userName
		}
		res.send({
			status: 200,
			data: {
				code: 0,
				doctorInfo: obj
			},
			msg: '查询成功'
		})
	} else {
		res.send({
			status: 500,
			msg: '查询失败'
		})
	}
})

// 更改医师 在线/离线 状态
router.post('/changeDoctorState', async (req, res) => {
	console.log(req.body)
	const {state} = req.body
	const { id } = req.body
	doctor.updateOne({id}, {state}, (err, docs) => {
		if (err) {
			throw err
		} else {
			res.send({
				status: 200,
				data: {
					code: 0,
				},
				msg: '修改成功'
			})
		}
	})
})

/* 导出router对象 */
module.exports = router